<!-- src/views/auth/LoginView.vue -->
<script setup lang="ts">
import { ref } from 'vue';
import { ElMessage, type FormInstance } from 'element-plus';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { useProjectStore } from '@/stores/project/project';
import { User, Lock } from '@element-plus/icons-vue';

const router = useRouter();
const userStore = useUserStore();
const projectStore = useProjectStore();

const form = ref({
  username: '',
  password: '',
});

const formRef = ref<FormInstance | null>(null);

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
};

const loading = ref(false);

const onSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    loading.value = true;
    await userStore.login(form.value.username, form.value.password);
    ElMessage.success('登录成功');

    // 根据角色跳转
    const role = userStore.user?.role;
    if (role === 'EMPLOYEE') {
      await router.push('/front');
    } else if (role === 'MANAGER') {
      await router.push('/admin');
    } else {
      ElMessage.error('未知角色，请联系管理员');
      await router.push('/login');
    }
  } catch (error) {
    console.error('登录失败:', error);
    ElMessage.error('登录失败，请检查用户名或密码');
  } finally {
    loading.value = false;
  }
};
</script>

<template>
  <div class="login-container">
    <el-card class="login-card">
      <h1>欢迎登录 {{ projectStore.getProjectName }}</h1>
      <h2>登录</h2>
      <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        @submit.prevent="onSubmit"
      >
        <el-form-item prop="username">
          <el-input v-model="form.username" placeholder="用户名" :prefix-icon="User" clearable />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="密码"
            :prefix-icon="Lock"
            show-password
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" native-type="submit" style="width: 100%">
            登录
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-link type="primary" @click="$router.push('/register')">没有账号？去注册</el-link>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
}

.login-card {
  width: 400px;
  padding: 20px;
}

h1 {
  text-align: center;
  margin-bottom: 10px;
  font-size: 24px;
  color: #409eff;
}

h2 {
  text-align: center;
  margin-bottom: 20px;
}
</style>